import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        list: [],
        // 输入框的值
        inputValue: '',
        nextId: 5,
        viewKey: 'all'
    },
    getters: {
        unDoneLength(state) {
            return state.list.filter(v => v.done === false).length
        },
        infoList(state) {
            if (state.viewKey == 'all') return state.list
            if (state.viewKey == 'undone') return state.list.filter(v => !v.done)
            if (state.viewKey == 'done') return state.list.filter(v => v.done)

            return state.list
        }
    },
    // mutations 函数中不能执行异步操作
    mutations: {
        initList(state, list) {
            state.list = list
        },
        // 为输入框赋值
        setInputValue(state, val) {
            state.inputValue = val
        },
        // 新增
        addItem(state) {
            let obj = {
                id: state.nextId,
                info: state.inputValue.trim(),
                done: false
            }
            state.list.push(obj);
            state.nextId++;
            state.inputValue = '';
            localStorage.setItem('vuex-todolist', JSON.stringify(state.list))
        },
        removeItem(state, id) {
            let index = state.list.findIndex(v => v.id == id);
            index > -1 ? state.list.splice(index, 1) : '';
            localStorage.setItem('vuex-todolist', JSON.stringify(state.list))
        },
        // 修改复选框状态
        stateChange(state, param) {
            let index = state.list.findIndex(v => v.id == param.id);
            index > -1 ? state.list[index].done = param.done : '';
            localStorage.setItem('vuex-todolist', JSON.stringify(state.list))
        },
        // 清除已完成
        clearAllDone(state) {
            state.list = state.list.filter(v => v.done == false);
            localStorage.setItem('vuex-todolist', JSON.stringify(state.list))
        },
        // 按需切换视图
        changeView(state, key) {
            state.viewKey = key
        }
    },
    // actions: 中定义异步操作
    actions: {
        getList(context) {
            //异步获取数据
            // axios.get('./list.json').then(({ data }) => {
            //     // console.log(data);
            //     context.commit('initList', data)
            // })

            let liststr = localStorage.getItem('vuex-todolist');
            // console.log(liststr);
            if (liststr && liststr != null) return context.commit('initList', JSON.parse(liststr))
            return []
        }

    },
    modules: {}
})